package com.trying.simpleioc.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.apache.log4j.Logger;
/**
 * 反射操作工具
 * @author dimi
 *
 */
public class ReflectionUtil {
	
	private static final Logger log=Logger.getLogger(ReflectionUtil.class);
	private ReflectionUtil(){}
	/**
	 * 生成实例
	 * @param cls
	 * @return
	 */
	public static Object newInstance(Class<?> cls){
		Object instance;
		try {
			instance=cls.newInstance();
		} catch (Exception e) {
			log.error(e);
			throw  new RuntimeException(e);
		} 
		return instance;
	}

	/**
	 * 调用方法
	 * @param obj
	 * @param method
	 * @param args
	 * @return
	 */
	public static Object invokeMethod(Object obj,Method method,Object... args){
		Object result;
		try {
			method.setAccessible(true);
			result=method.invoke(obj, args);
		} catch (Exception e) {
			log.error(e);			
			throw new RuntimeException(e);
		}  
		return result;
	}
	
	/**
	 * 设置属性
	 */
	public static void setFeild(Field field,Object obj,Object value){
		field.setAccessible(true);
		try {
			field.set(obj, value);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
		}
	}
	
}
